package com.xx.pmis.web.actions;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.xx.pmis.model.Medicine;
import com.xx.pmis.model.Shop;
import com.xx.pmis.services.MedicineService;
import com.xx.pmis.services.ShopService;
import com.xx.pmis.web.forms.MedicineForm;
import com.xx.pmis.web.util.AccountUtil;
import com.xx.pmis.web.util.CurrentDate;
import com.xx.pmis.web.util.Rand;

/**
 * @class 药品Action类 <br>
 * 
 * @editor 石星星 @Date 2011-9-21 下午03:17:42 <br>
 * @version jdk_1.5.0
 */
public class MedicineAction extends PMISBaseAction {
	private static final Log log = LogFactory.getLog(MedicineAction.class);

	MedicineService medicineService = getPMISServices().getMedicineService();
	ShopService shopService = getPMISServices().getShopService();

	AccountUtil accountUtil = new AccountUtil();

	// 查询所有药品
	public ActionForward listMedicine(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		List<Medicine> all = null;
		try {
			all = medicineService.getAllMedicineByCondition(" order by medicineDate desc");
		} catch (Exception e) {
			String errorPage = "【物资管理/药品】查询【药品】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		request.setAttribute("medicineList", all);
		return mapping.findForward("listMedicine");
	}

	// 新增
	public ActionForward addMedicine(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		List<?> shopList = null;
		try {
			shopList = shopService.getAllShopByShopType("1");
		} catch (Exception e) {
			String errorPage = "【物资管理/药品/新增】查询【商店】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		request.setAttribute("shopList", shopList);
		request.setAttribute("medicineDate", CurrentDate.currentDate());
		request.setAttribute("position", "药品/新增");
		return mapping.findForward("addMedicine");
	}

	// 新增，处理方法
	public ActionForward addMedicine_Do(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		MedicineForm f = (MedicineForm) form;

		String medicineName = f.getMedicineName(); // 药品名称
		// String medicineState = f.getMedicineState(); // 用完 0，未完 1
		String medicineDate = f.getMedicineDate(); // 购买日期，结算时作为流水账的记账日期
		String validPeriod = f.getValidPeriod(); // 有效期
		String medicineExpense = f.getMedicineExpense(); // 费用，购买的费用，用于计算折扣
		String medicineDesc = f.getMedicineDesc(); // 描述
		String shopID = f.getShopID();
		String manufacturer = f.getManufacturer(); // 生产厂家

		Medicine medicine = new Medicine();
		medicine.setMedicineID(CurrentDate.currentYear() + Rand.getRand());
		medicine.setMedicineName(medicineName);
		medicine.setMedicineState("1");
		medicine.setMedicineDate(medicineDate);
		medicine.setValidPeriod(validPeriod);
		medicine.setMedicineExpense(accountUtil.if1ZeroTo2Zero(medicineExpense));
		medicine.setMedicineDesc(medicineDesc);
		medicine.setMedicinePay("1");

		medicine.setShopID(shopID);
		medicine.setManufacturer(manufacturer);
		try {
			medicineService.saveOrUpdateMedicine(medicine);
		} catch (Exception e) {
			String errorPage = "【物资管理/药品/新增】保存或更新【药品】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}

		listMedicineByPage(mapping, form, request, response);
		return mapping.findForward("listMedicine");
	}

	// 编辑
	public ActionForward editMedicine(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		String medicineID = request.getParameter("medicineID");
		String pageNum = request.getParameter("pageNum");

		List<?> shopList = null;
		try {
			shopList = shopService.getAllShop();
		} catch (Exception e) {
			String errorPage = "【物资管理/药品/编辑】查询【商店】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		request.setAttribute("shopList", shopList);
		Medicine medicine = null;
		try {
			medicine = medicineService.getMedicineByMedicineID(medicineID);
		} catch (Exception e) {
			String errorPage = "【物资管理/药品/编辑】根据【药品ID】查询该【药品】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		Shop shop = null;
		try {
			shop = shopService.getShopByShopID(medicine.getShopID());
		} catch (Exception e) {
			String errorPage = "【物资管理/药品/编辑】根据ID查询该【商店】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		request.setAttribute("medicine", medicine);
		request.setAttribute("shopName", shop.getShopName());
		request.setAttribute("pageNum", pageNum);
		request.setAttribute("position", "药品/编辑");
		return mapping.findForward("editMedicine");
	}

	// 编辑，处理方法
	public ActionForward editMedicine_Do(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		String pageNum = request.getParameter("pageNum");

		MedicineForm f = (MedicineForm) form;
		String medicineID = f.getMedicineID();
		String medicineName = f.getMedicineName(); // 药品名称
		// String medicineState = f.getMedicineState(); // 用完 0，未完 1
		String medicineDate = f.getMedicineDate(); // 购买日期，结算时作为流水账的记账日期
		String validPeriod = f.getValidPeriod(); // 有效期
		String medicineExpense = f.getMedicineExpense(); // 费用，购买的费用，用于计算折扣
		String medicineDesc = f.getMedicineDesc(); // 描述
		String shopID = f.getShopID();
		String manufacturer = f.getManufacturer(); // 生产厂家

		Medicine medicine = null;
		try {
			medicine = medicineService.getMedicineByMedicineID(medicineID);
		} catch (Exception e) {
			String errorPage = "【物资管理/药品/编辑】根据【药品ID】查询该【药品】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		medicine.setMedicineName(medicineName);
		// medicine.setMedicineState(medicineState);
		medicine.setMedicineDate(medicineDate);
		medicine.setValidPeriod(validPeriod);
		medicine.setMedicineExpense(accountUtil.if1ZeroTo2Zero(medicineExpense));
		medicine.setMedicineDesc(medicineDesc);
		medicine.setManufacturer(manufacturer);

		medicine.setShopID(shopID);
		try {
			medicineService.saveOrUpdateMedicine(medicine);
		} catch (Exception e) {
			String errorPage = "【物资管理/药品/编辑】保存或更新【药品】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}

		request.setAttribute("pageNum", pageNum);
		listMedicineByPage(mapping, form, request, response);
		return mapping.findForward("listMedicine");
	}

	// 删除
	public ActionForward delMedicine(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		String pageNum = request.getParameter("pageNum");

		Medicine medicine = null;
		MedicineForm f = (MedicineForm) form;
		String[] ids = f.getIds();
		for (int i = 0; i < ids.length; i++) {
			try {
				medicine = medicineService.getMedicineByMedicineID(ids[i]);
			} catch (Exception e) {
				String errorPage = "【物资管理/药品/删除】根据【药品ID】查询该【药品】异常！" + e.toString();
				log.info(errorPage);
				request.setAttribute("errorPage", errorPage);
				request.setAttribute("position", "出错了");
				return mapping.findForward("errorPage");
			}
			try {
				medicineService.deleteMedicine(medicine);
			} catch (Exception e) {
				String errorPage = "【物资管理/药品/删除】删除【药品】异常！" + e.toString();
				log.info(errorPage);
				request.setAttribute("errorPage", errorPage);
				request.setAttribute("position", "出错了");
				return mapping.findForward("errorPage");
			}
		}

		request.setAttribute("pageNum", pageNum);
		listMedicineByPage(mapping, form, request, response);
		return mapping.findForward("listMedicine");
	}

	// 结算
	public ActionForward payMedicine(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String medicineID = request.getParameter("medicineID");
		String pageNum = request.getParameter("pageNum");

		Medicine medicine = new Medicine();
		try {
			medicine = medicineService.getMedicineByMedicineID(medicineID);
		} catch (Exception e) {
			String errorPage = "【物资管理/药品/结算】根据【药品ID】查询该【药品】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		// 生成记账凭证
		accountUtil.payExpenseToAccount(medicine.getMedicineDate(), "0030006", "1", medicine.getMedicineExpense(),
				"购买", medicine.getMedicineName());

		// 更新结算状态，结算完成为"0"
		medicine.setMedicinePay("0");
		try {
			medicineService.saveOrUpdateMedicine(medicine);
		} catch (Exception e) {
			String errorPage = "【物资管理/药品/新增】保存或更新【药品】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}

		request.setAttribute("pageNum", pageNum);
		listMedicineByPage(mapping, form, request, response);
		return mapping.findForward("listMedicine");
	}

	// 明细
	public ActionForward detailMedicine(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		String medicineID = request.getParameter("medicineID");

		Medicine medicine = null;
		try {
			medicine = medicineService.getMedicineByMedicineID(medicineID);
		} catch (Exception e) {
			String errorPage = "【物资管理/药品/明细】根据【药品ID】查询该【药品】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}

		request.setAttribute("medicine", medicine);
		request.setAttribute("position", "药品/明细");
		return mapping.findForward("detailMedicine");
	}

	// 分页显示
	public ActionForward listMedicineByPage(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		int PAGESIZE = 20;// 每页记录数
		int totalPage = 1;// 总页数

		// 查询总用户记录数
		int count = 0;
		try {
			count = medicineService.getCountOfMedicineByCondition("");
		} catch (Exception e) {
			String errorPage = "【物资管理/药品】查询【药品】数目异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		request.setAttribute("count", count);
		if (count % PAGESIZE == 0) {
			totalPage = count / PAGESIZE;
		} else {
			totalPage = count / PAGESIZE + 1;
		}

		request.setAttribute("totalPage", totalPage);
		// 声明要翻的页
		String pageNum = "1";
		try {
			String thisPageNum = request.getParameter("pageNum");
			// 如果传了页码参数
			if (thisPageNum != null && thisPageNum.length() != 0) {
				pageNum = thisPageNum;
			}
		} catch (RuntimeException e) {
			log.info("" + e.toString());
		}
		log.info("page:" + pageNum);
		request.setAttribute("pageNum", pageNum);
		List<Medicine> medicineList = null;
		List<Medicine> medicineListTemp = new ArrayList<Medicine>();
		try {
			medicineList = medicineService.getAllMedicineByConditionByPage(" order by medicineDate desc", Integer
					.parseInt(pageNum), PAGESIZE);
			for(Medicine medicine : medicineList) {
				Shop shop = new Shop();
				try {
					shop = shopService.getShopByShopID(medicine.getShopID());
				} catch (Exception e) {
					String errorPage = "【物资管理/葡萄酒/分页显示】根据商店ID查询【商店】异常！" + e.toString();
					log.info(errorPage);
				}
				medicine.setShopName(shop.getShopName());
				medicineListTemp.add(medicine);
			}
		} catch (Exception e) {
			String errorPage = "【物资管理/药品】查询【药品】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		request.setAttribute("medicineList", medicineListTemp);
		request.setAttribute("PAGESIZE", PAGESIZE);
		// 如果要翻的这页是第一页
		if ("1".equals(pageNum)) {
			// 设置noUp为yes(界面上用此控制'首页'与'上一页'按钮失效)
			request.setAttribute("noUp", "yes");
		}

		// 如果要翻的这页是最后页
		if (totalPage == Integer.parseInt(pageNum)) {
			// 设置noDown为yes(界面上用此控制'下一页'与'尾页'按钮失效)
			request.setAttribute("noDown", "yes");
		}

		request.setAttribute("action", "medicine.do");
		request.setAttribute("position", "物资管理/药品");
		return mapping.findForward("listMedicine");
	}

	// 更新库存状态
	public ActionForward updateMedicineState(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		String medicineID = request.getParameter("medicineID");
		String state = request.getParameter("state");
		String pageNum = request.getParameter("pageNum");

		Medicine medicine = null;
		try {
			medicine = medicineService.getMedicineByMedicineID(medicineID);
		} catch (Exception e) {
			String errorPage = "【物资管理/药品】根据【药品ID】查询该【药品】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}

		if ("yongwan".equals(state)) {// 用完
			medicine.setMedicineState("1");
		} else if ("weiwan".equals(state)) {// 未完
			medicine.setMedicineState("0");
		} else {
			log.error("输入参数应为“yongwan”，“weiwan”。");
		}

		try {
			medicineService.saveOrUpdateMedicine(medicine);
		} catch (Exception e) {
			String errorPage = "【物资管理/药品】保存或更新【药品】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}

		request.setAttribute("pageNum", pageNum);
		request.setAttribute("position", "资管理/药品");
		listMedicineByPage(mapping, form, request, response);
		return mapping.findForward("listMedicine");
	}

}